class TraintaskController < ApplicationController
  before_filter :sys_before_log

  #得到trainTask列表，带分页
  def getTrainTasks
    pageBegin =  params[:start].to_i
    pageEnd =  params[:limit].to_i
    conditionsStr = ""                                                          #定义一个str，里面存储所有的搜索条件，后面他会不断被加长
    conditionsHash = Hash.new                                                   #定义一个hash，里面存储所有的搜索索引，后面他会不断被加长
    if params[:begin_time].to_s != ""                                           #设置开始时间搜索条件范围，大于结束时间
      if conditionsStr == ""
        conditionsStr = "begin_time >= :begin_time_search"
      else
        conditionsStr = conditionsStr + " AND begin_time >= :begin_time_search"
      end
      conditionsHash[:begin_time_search] = Time.parse(params[:begin_time])#     现已经全改为北京时间注释掉by jerry  -(60*60*8)
    end
    if params[:end_time].to_s != ""                                             #设置开始时间搜索条件范围，小于结束时间
      if conditionsStr == ""
        conditionsStr = "begin_time <= :end_time_search"
      else
        conditionsStr = conditionsStr + " AND begin_time <= :end_time_search"
      end
      conditionsHash[:end_time_search] = Time.parse(params[:end_time])          # 现已经全改为北京时间注释掉by jerry  -(60*60*8)
    end
    if params[:train_id].to_s != ""                                             #设置列车id限制条件
      if conditionsStr == ""
        conditionsStr = "train_id = :train_id"
      else
        conditionsStr = conditionsStr + " AND train_id = :train_id"
      end
      conditionsHash[:train_id] = params[:train_id]
    end
    if params[:begin_time].to_s == "" && params[:end_time].to_s == "" && params[:train_id].to_s == ""    #如果所有的参数都没设置，那么就只取当天的记录,且按照正序排列
      dateStr = Time.zone.now.to_s[0,10]
      yesdayStr = (Time.zone.now - 86400).to_s[0,10]                            #得到昨天的日期
      if conditionsStr == ""
        conditionsStr = "begin_time like :begin_time OR begin_time like :begin_time2"
      else
        conditionsStr = conditionsStr + " AND begin_time like :begin_time OR begin_time like :begin_time2"        #这句逻辑可能不对，请查验
      end
      conditionsHash[:begin_time] = '%' + yesdayStr + '%'                       #查出来昨天日期的任务
      conditionsHash[:begin_time2] = '%' + dateStr + '%'                         #查出今天日期的任务
      allTrainTaskes = TrainTask.find(:all,:conditions=>[conditionsStr,conditionsHash])
      trainTaskes = TrainTask.find(:all,:conditions=>[conditionsStr,conditionsHash],:limit =>pageBegin.to_s+","+pageEnd.to_s,:order=> 'begin_time DESC')
    else                                                                        #如果有参数设置，那么取出合适的任务,按照倒序排列
      allTrainTaskes = TrainTask.find(:all,:conditions=>[conditionsStr,conditionsHash])
      trainTaskes = TrainTask.find(:all,:conditions=>[conditionsStr,conditionsHash],:limit =>pageBegin.to_s+","+pageEnd.to_s,:order=> 'begin_time DESC')
    end
    for trainTask in trainTaskes                                                #循环所有的trainTaskes，为了给其赋上新值
      if trainTask.is_end == 3                                                  #如果状态等于电力调整结束
        is_end = 2                                                              #一开始认为已经完成了
        for maintenance in trainTask.maintenances                                  #检查所有的maintenance是否已经完成
          if maintenance.check_out_time == nil                                    #只要有一个没有打卡结束
            is_end = 3                                                            #那状态还是状态等于电力调整结束
            trainTask.is_end = is_end
            trainTask.save!
          end
        end
      elsif trainTask.is_end ==0                                                #如果状态为开始打卡
        is_end = 2                                                              #一开始认为已经完成了
        for maintenance in trainTask.maintenances                                #检查所有的maintenance是否已经完成
          if maintenance.check_out_time == nil                                  #只要有一个没有打卡结束
            is_end = 0                                                          #那状态还是开始打卡
            trainTask.is_end = is_end
            trainTask.save!
          end
        end
      end
    end
    jsonStr="{root:"+trainTaskes.to_json(:include => [:train])+",total:"+allTrainTaskes.length.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  #通过列车ID，获取该列车的所有维修任务
  def getTasksById
    trainTasks = TrainTask.find_all_by_train_id params[:train_id]
    total = trainTasks.length
    jsonStr="{root:"+trainTasks.to_json()+",total:"+total.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  #新建一个列车维护任务
  def create
    begin
      ttask = TrainTask.find(:first,:conditions => ['stop_track = ?',params[:stop_track].to_s],:order => 'created_at DESC')
      if ttask.is_end != 1
        info = '当前股道有动车在检修，不能在该股道新增检修任务，如果该股道上检修任务已完成，请结束检修任务再新建新的检修任务。'
      else
        trainTask = TrainTask.new                                               #在此trainTask已经变成了全新生成的对象了，没有id属性
        trainTask.begin_time = params[:begin_time]
        trainTask.sn = params[:sn]
        trainTask.train_id = params[:train_id]
#        template = Template.find params[:template_id]                             #找到模板
#        trainTask.sub_type = template.sub_type                                    #找到模板的动静态属性
        trainTask.description = params[:description]
        trainTask.stop_track = params[:stop_track]
        trainTask.device_id = params[:device_id]
        #计算到达交路
        train = trainTask.train                                                 #得到列车任务所对应的列车
        nowDate = Time.now.to_date                                              #得到当前日期
        if train.router_date                                                    #判断是否已经设置交路
          days = (nowDate - train.router_date)                                  #得到列车交路的设置时间
          sequence = (days % train.router_number).to_i                          #当前时间 - 交路设置时间的结果，和交路数取余，即可得到交路编号
          router = TrainRouter.findByTrainIdAndSequence(train.id,sequence).router #通过列车id和队列得到交路对象
          trainTask.arrive_train_number = router.train_number.split("、")[-1]    #赋值到达交路，以顿号隔开，得到倒数第一个数据
        else
          trainTask.arrive_train_number = '未设置'
        end
        trainTask.save!                                                         #至此trainTask已经存储完毕，下面是将任务模板的信息存入维护单元列表中
        standardMaintenances =
          StandardMaintenance.find_all_by_template_id params[:template_id]      #得到标准任务模板的列表
        for standard_maintenance in standardMaintenances                        #遍历标准任务模板列表
          maintenance = Maintenance.new                                         #新建一条维护记录
          maintenance.work_id = standard_maintenance.work_id                    #维护单元的工作id等于标准任务的工作id
          maintenance.team_id = standard_maintenance.team_id                    #维护单元的团队id等于标准任务的团队id
          maintenance.description = standard_maintenance.description            #维护单元的详情描述等于标准任务的详情描述
          maintenance.train_task_id = trainTask.id                               #维护单元的列车任务id等于当前列车任务的id
          maintenance.begin_time = trainTask.begin_time +
            standard_maintenance.begin_minute * 60                              #起始时间等于火车的起始时间加上开始间隔时间
          during_minute = standard_maintenance.begin_minute +
            standard_maintenance.during_minute                                  #持续时间，等于起始间隔时间加上持续时间。这是中间量，不存入数据库
          maintenance.finish_time = trainTask.begin_time +
            during_minute * 60                                                  #结束时间等于火车起始时间加上总时间
          maintenance.dynamic_flag = standard_maintenance.flag
          maintenance.dynamic_un_start_minute = standard_maintenance.dynamic_during_minute
          
          maintenance.save!
        end
        info = 'success'
      end
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info( params[:controller], params[:action], request.remote_ip ,info)
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text => result,:layout => false
  end

  #删除列车维护任务
  def delete
    begin
      ids= params[:id][1..params[:id].length-2].split(',')
      TrainTask.destroy(ids)
      info = 'success'
    rescue Exception=>e
      logger.info e
      info = '删除异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  #编辑一条列车维护任务
  def edit
    trainTask = TrainTask.find(params[:id])
    jsonStr = trainTask.to_json()
    render :text=>jsonStr,:layout=>false
  end

  #更新一条列车维护任务
  def update
    begin
      trainTask = TrainTask.find(params[:id])                                   #根据id找到对象
      oldBeginTime = trainTask.begin_time.to_s                                  #得到过去项目的开始时间
      beginTime = params[:begin_time]                                           #将begin_time处理成可以进行时间加减的格式
      beginTime = beginTime + ' +0800'                                          #同上
      adjustSecond = (DateTime.parse(beginTime) -
          DateTime.parse(oldBeginTime))*24*60*60                                #得到差距的秒数
      #      if trainTask.sn == params[:sn]                                            #如果参数sn和自带的sn相等
      #        trainTask.begin_time = params[:begin_time]                              #就只是赋值其他的参数
      #        #trainTask.train_id = params[:train_id]
      #        trainTask.description = params[:description]
      #        trainTask.stop_track = params[:stop_track]
      #        trainTask.device_id = params[:device_id]
      #        trainTask.save
      #        maintenances = Maintenance.findByTrainTaskId params[:id]                #得到标准任务模板的列表
      #        for maintenance in maintenances                                         #遍历标准任务模板列表
      #          maintenance.begin_time = maintenance.begin_time + adjustSecond        #调整子任务的开始时间
      #          maintenance.finish_time = maintenance.finish_time + adjustSecond      #调整子任务的结束时间
      #          maintenance.save!
      #        end
      #        info = 'success'
      #      else                                                                      #如果参数sn不相等
      #        exit = TrainTask.find_by_sn params[:sn]                                 #就以sn找到对象
      #        if exit == nil                                                          #如果没有找到，就使用这个sn
      trainTask.sn = params[:sn]
      #trainTask.train_id = params[:train_id]
      trainTask.begin_time = params[:begin_time]
      trainTask.description = params[:remark]
      trainTask.stop_track = params[:stop_track]
      trainTask.device_id = params[:device_id]
      trainTask.save
      maintenances = Maintenance.findByTrainTaskId params[:id]              #得到标准任务模板的列表
      for maintenance in maintenances                                       #遍历标准任务模板列表
        maintenance.begin_time = maintenance.begin_time + adjustSecond      #调整子任务的开始时间
        maintenance.finish_time = maintenance.finish_time + adjustSecond    #调整子任务的结束时间
        maintenance.save!
      end
      info = 'success'
      #        else
      #          info = '该检修编号已存在，请更换！'
      #        end
      #      end
    rescue Exception=>e
      logger.info e
      info = '更新异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  #得到正在进行的任务列表，并且自动计算列车的到达和离开的车次
  def getActiveTasks
    trainTasks = TrainTask.findAllByIsEnd 0                                     #查找没有结束的trainTask列表
    total = trainTasks.length
    for trainTask in trainTasks
      train = trainTask.train                                                   #得到列车任务所对应的列车
      nowDate = Time.now.to_date                                                #得到当前日期
      if(train && train.router_date)                                                     #如果有交路设置日期，就说明其交路已经设置
        trainDate = train.router_date                                           #得到列车交路的设置时间
        #计算离开交路
        days = (nowDate - trainDate)+1                                          #计算明天的时间的差值
        sequence = (days % train.router_number).to_i                            #当前时间 - 交路设置时间的结果，和交路数取余，即可得到交路编号
        router = TrainRouter.findByTrainIdAndSequence(train.id,sequence).router #通过列车id和队列得到交路对象
        trainTask.leave_train_number = router.train_number.split("、")[0]      #赋值出发交路
      else
        trainTask.arrive_train_number = '未设置'                                 #赋值出发交路
        trainTask.leave_train_number = '未设置'                                  #赋值出发交路
      end
    end
    jsonStr="{root:"+trainTasks.to_json(:include => [:train])+",total:"+total.to_s+"}"
    logger.info jsonStr
    render :text => jsonStr,:layout => false
  end

  #在载入chart的时候，提供相关的trainTask的数据
  def getStartTasks
    trainTask = TrainTask.find(params[:trainTaskId])
    train = trainTask.train                                                     #得到列车任务所对应的列车
    nowDate = Time.now.to_date                                                  #得到当前日期
    if(train.router_date)                                                       #如果有交路设置日期，就说明其交路已经设置
      trainDate = train.router_date                                             #得到列车交路的设置时间
      #计算离开交路
      days = (nowDate - trainDate)+1
      sequence = (days % train.router_number).to_i                              #当前时间 - 交路设置时间的结果，和交路数取余，即可得到交路编号
      router = TrainRouter.findByTrainIdAndSequence(train.id,sequence).router   #通过列车id和队列得到交路对象
      trainTask.leave_train_number = router.train_number.split("、")[0]         #赋值出发交路
    else
      trainTask.arrive_train_number = '未设置'                                   #赋值出发交路
      trainTask.leave_train_number = '未设置'                                    #赋值出发交路
    end
    jsonStr=trainTask.to_json(:include => [:train])
    render :text => jsonStr,:layout => false
  end

  #结束一个列车维护任务，将标志位设为1
  def finishTrainTask
    begin
      trainTask = TrainTask.find(params[:trainTaskId])
      trainTask.is_end = 1
      trainTask.maintenances.each do |maintenance|
        case maintenance.flag
        when '1'
          maintenance.flag = '9'
        when '2'
          maintenance.check_out_time = Time.now
          maintenance.flag = '9'
        when '4'
          maintenance.dynamic_check_out_time = Time.now
          maintenance.flag = '7'
        when '5'
          maintenance.dynamic_check_out_time = Time.now
          maintenance.flag = '9'
        end
        maintenance.save!
      end
      trainTask.end_time = Time.now
      trainTask.save!
      info = 'success'
    rescue Exception=>e
      logger.info e
      info = '操作异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end


  #设置断电已经完成，可以进行打卡上工了
  def setTraintaskBegin
    begin
      trainTask = TrainTask.find(params[:trainTaskId])
      unless trainTask.check_out_time
        trainTask.check_out_time = Time.now 
        trainTask.is_end = 2
        trainTask.maintenances.each do |maintenance|
          maintenance.flag = '2'
          maintenance.save!
        end
        trainTask.save!
      end
      info = 'success'
    rescue Exception => e
      logger.info e
      info = '操作异常'
    end
    render :text=>info, :layout=>false
  end

  def setPowerBegin
    begin
      trainTask = TrainTask.find(params[:trainTaskId])
      unless trainTask.power_time && trainTask.is_end == 0
        trainTask.power_time = Time.now
        trainTask.is_end = 3
        trainTask.maintenances.each do |maintenance|
          case maintenance.flag
          when '2'
            #如果小组有动态作业，供电后开始动态作业，如果小组没有动态作业，供电后继续开始静态作业
            if maintenance.dynamic_flag != 0
              maintenance.check_out_time = Time.now
              maintenance.flag = '5'
            end
          when '3'
            maintenance.flag = '4'
          end
          maintenance.save!
        end
        trainTask.save!
      end
      info = 'success'
    rescue Exception => e
      logger.info e
      info = '操作异常'
    end
    render :text=>info, :layout=>false
  end

  def add_check_out_time
    train_tasks = TrainTask.find :all
    begin
      for train_task in train_tasks
        train_task.check_out_time = train_task.begin_time
        train_task.save!
      end
      info = 'success'
    rescue Exception=>e
      logger.info e
      info = '操作异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false

  end


end